﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Threading;

namespace THO7AlgoritmTimerApplication
{
    public static class Filters
    {
        public static Bitmap MedianFilter(Bitmap sourceImage, int Size)
        {
            Bitmap returnImage = new Bitmap(sourceImage);

            FastPixelAccess srcImg = new FastPixelAccess(sourceImage);
            FastPixelAccess retImg = new FastPixelAccess(returnImage);
            srcImg.Lock();
            retImg.Lock();

            int ApetureMin = -(Size / 2);
            int ApetureMax = (Size / 2);
            for (int x = 0; x < retImg.Width; x++)
            {
                for (int y = 0; y < retImg.Height; y++)
                {
                    List<int> RValues = new List<int>();
                    List<int> GValues = new List<int>();
                    List<int> BValues = new List<int>();
                    for (int x2 = ApetureMin; x2 < ApetureMax; x2++)
                    {
                        int TempX = x + x2;
                        if (TempX >= 0 && TempX < retImg.Width)
                        {
                            for (int y2 = ApetureMin; y2 < ApetureMax; y2++)
                            {
                                int TempY = y + y2;
                                if (TempY >= 0 && TempY < retImg.Height)
                                {
                                    Color color = srcImg.GetPixel(TempX, TempY);
                                    RValues.Add(color.R);
                                    GValues.Add(color.G);
                                    BValues.Add(color.B);
                                }
                            }
                        }
                    }
                    RValues.Sort();
                    GValues.Sort();
                    BValues.Sort();
                    Color MedianPixel = Color.FromArgb(RValues[RValues.Count / 2], GValues[GValues.Count / 2], BValues[BValues.Count / 2]);
                    retImg.SetPixel(x, y, MedianPixel);
                }
            }

            srcImg.Unlock(true);
            retImg.Unlock(true);
            return returnImage;
        }

    }
}
